<template>
  <div class="wrapper">
    <!-- 顶部栏 -->
    <header class="topbar">
      <div class="topbar-content">
        <h1 class="title">我的店铺</h1>
        <div class="topbar-actions">
          <!-- 只保留退出登录在右上角 -->
          <button class="logout-btn" @click="logout" aria-label="退出登录">
            <span class="logout-icon">↩</span> 退出登录
          </button>
        </div>
      </div>
    </header>

    <div class="container">
      <!-- 操作按钮栏 - 新增 -->
      <div class="action-bar">
        <button class="wallet-btn" @click="toWallet" aria-label="我的钱包">
          <span class="wallet-icon">💰</span> 我的钱包
        </button>
        <button class="add" @click="toCreate" aria-label="创建店铺">
          <span class="add-icon">＋</span> 创建店铺
        </button>
      </div>
      <!-- 筛选标签 -->
      <nav class="tabs" role="tablist">
        <span v-for="t in tabs" :key="t.value" :class="['tab', { active: currentTab === t.value }]" role="tab"
          :aria-selected="currentTab === t.value" @click="currentTab = t.value">
          {{ t.label }}
        </span>
      </nav>

      <!-- 列表区域 -->
      <div v-if="loading" class="state loading">
        <div class="loading-spinner"></div>
        <p>正在加载店铺信息...</p>
      </div>
      <div v-else-if="!filteredList.length" class="state empty">
        <div class="empty-icon">🏪</div>
        <p>暂无店铺</p>
        <p>点击右上角<i>创建店铺</i>开始使用</p>
      </div>
      <div v-else class="list">
        <article v-for="b in filteredList" :key="b.id" class="card"
          :class="{ clickable: mapStatus(b).value === 'approved' }" @click="enterIfApproved(b)">
          <div class="card-header">
            <div class="name">{{ b.businessName || '未命名店铺' }}</div>
            <span class="badge" :class="'s-' + mapStatus(b).value">
              {{ mapStatus(b).label }}
            </span>
          </div>

          <div class="meta">
            <span v-if="b.businessAddress" class="address">
              <span class="meta-icon">📍</span> {{ b.businessAddress }}
            </span>
            <span v-if="b.startPrice != null" class="price">
              <span class="meta-icon">💰</span> 起送 ¥{{ Number(b.startPrice).toFixed(0) }}
            </span>
            <span class="open" :class="{ on: b.isOpen === true }" v-if="b.isOpen != null">
              <span class="status-dot" :class="{ on: b.isOpen === true }"></span>
              {{ b.isOpen ? '营业中' : '休息中' }}
            </span>
          </div>

          <p v-if="mapStatus(b).value !== 'approved'" class="tip">
            ⓘ 仅审核通过后可进入管理
          </p>
        </article>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'businessMine',
  data() {
    return {
      loading: false,
      error: '',
      usedApi: '',
      list: [],
      currentTab: 'all',
      tabs: [
        { label: '全部', value: 'all' },
        { label: '审核中', value: 'reviewing' },
        { label: '已通过', value: 'approved' },
        { label: '未通过', value: 'notApproved' },
      ],
      token: {},
      user: {}
    }
  },
  created() {
    this.token = localStorage.getItem('token');
    this.$axios.get(`/user`, {
      headers: {
        'Authorization': `Bearer ${this.token}`
      }
    }).then(response => {
      this.user = response.data.data;
      this.fetchList();
    }).catch(error => {
      console.error(error);
    });
  },
  methods: {
    // 提取状态码（兼容 "opening-营业中" 这类"码-中文"）
    decodeStatusCode(v) {
      const s = (v ?? '').toString().trim().toLowerCase()
      const allowed = new Set(['opening', 'closing', 'banned', 'offline', 'reviewing'])
      return allowed.has(s) ? s : 'reviewing'
    },
    // 分组：用于筛选和按钮权限
    groupStatus(code) {
      if (code === 'opening' || code === 'closing') return 'approved'
      if (code === 'banned' || code === 'offline') return 'notApproved'
      return 'reviewing'
    },

    normalize(raw = {}) {
      const code = this.decodeStatusCode(raw.businessStatus)

      return {
        id: raw.id,
        businessName: raw.businessName,
        businessAddress: raw.businessAddress,
        startPrice: raw.startPrice,
        deliveryPrice: raw.deliveryPrice,
        businessImg: raw.businessImg,
        businessExplain: raw.businessExplain,
        userId: raw.userId,
        statusCode: code,                     // opening / closing / banned / offline / reviewing...
        statusGroup: this.groupStatus(code),  // approved / notApproved / reviewing

        isOpen: raw.isOpen ?? null            // 若你后端有此字段就保留；没有可删
      }
    },


    // 列表拉取后
    async fetchList() {
      this.loading = true;
      try {
        const res = await this.$axios.get(`businesses/${this.user.id}/boss`, {
          headers: { Authorization: `Bearer ${this.token}` }
        })
        const raw = res.data.data
        let list = Array.isArray(raw) ? raw.map(this.normalize) : []
        this.list = list
      } catch (error) {
        console.error('获取店铺列表失败:', error)
      } finally {
        this.loading = false;
      }
    },

    mapStatus(b) {
      const g = b?.statusGroup
      if (g === 'approved') return { value: 'approved', label: '已通过' }
      if (g === 'notApproved') return { value: 'notApproved', label: '未通过' }
      return { value: 'reviewing', label: '审核中' }
    },

    enterIfApproved(b) {
      if (this.mapStatus(b).value !== 'approved') return
      const to = { name: 'BusinessModify', path: `/business/modify/${b.id}` }
      try { this.$router.push({ name: to.name, params: { id: b.id } }) }
      catch { this.$router.push(to.path) }
    },

    // 创建店铺
    toCreate() {
      const to = { name: 'BusinessCreate', path: '/business/create' }
      if (this.$router) {
        try { this.$router.push({ name: to.name }) }
        catch { this.$router.push(to.path) }
      } else {
        window.location.href = to.path
      }
    },

    // 退出登录
    logout() {
      localStorage.removeItem('token')
      // 修正路由拼写错误
      this.$router.push('/index')
    },
    toWallet() {
      const to = { name: 'Wallet', path: '/wallet' }
      if (this.$router) {
        try { this.$router.push({ name: to.name }) }
        catch { this.$router.push(to.path) }
      } else {
        window.location.href = to.path
      }
    }
  },

  computed: {
    filteredList() {
      const cur = this.currentTab
      const arr = Array.isArray(this.list) ? this.list : []
      if (cur === 'all') return arr
      return arr.filter(b => this.mapStatus(b).value === cur)
    }
  }
}
</script>

<style scoped>
/* 颜色变量挂在 .wrapper（避免 :root + scoped 失效） */
.wrapper {
  --primary: #4361ee;
  --primary-light: #4895ef;
  --secondary: #3f37c9;
  --success: #4cc9f0;
  --danger: #f72585;
  --warning: #f8961e;
  --info: #7209b7;
  --light: #f8f9fa;
  --dark: #212529;
  --bg: #f0f2f5;
  --card-bg: #ffffff;
  --text: #333333;
  --text-light: #6c757d;
  --border: #dee2e6;
}

.wrapper {
  min-height: 100vh;
  background: var(--bg);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: var(--text);
}

/* 顶部栏 */
.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
  color: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.topbar-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 70px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title {
  font-size: 22px;
  font-weight: 700;
  letter-spacing: 0.5px;
  margin: 0;
}

.topbar-actions {
  display: flex;
  gap: 12px;
}

.add,
.logout-btn {
  height: 40px;
  padding: 0 16px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
  font-size: 14px;
}

.add {
  background: rgba(255, 255, 255, 0.9);
  color: var(--primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.add:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.logout-btn {
  background: rgba(255, 255, 255, 0.15);
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.logout-btn:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-2px);
}

.add-icon,
.logout-icon {
  font-size: 18px;
}

/* 容器：底部留出 Footer 的高度 14vw，再加 16px 缓冲，避免列表被遮住 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 20px;
  padding-bottom: calc(14vw + 24px);
}

/* 筛选标签 */
.tabs {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 24px;
  padding: 4px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tab {
  padding: 8px 16px;
  border-radius: 8px;
  background: transparent;
  color: var(--text-light);
  cursor: pointer;
  user-select: none;
  transition: all 0.3s ease;
  font-weight: 500;
}

.tab.active {
  background: var(--primary);
  color: #fff;
  box-shadow: 0 2px 6px rgba(67, 97, 238, 0.3);
}

.tab:not(.active):hover {
  background: rgba(67, 97, 238, 0.1);
  color: var(--primary);
}

/* 列表 */
.list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

/* 操作按钮栏 */
.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.wallet-btn, .add {
  height: 44px;
  padding: 0 20px;
  border: none;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  font-size: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.wallet-btn {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
}

.wallet-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}

.add {
  background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
  color: white;
}

.add:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
}

.wallet-icon, .add-icon {
  font-size: 18px;
}

@media (min-width: 768px) {
  .list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 1024px) {
  .list {
    grid-template-columns: repeat(3, 1fr);
  }
}

.card {
  background: var(--card-bg);
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, var(--primary) 0%, var(--secondary) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.card.clickable {
  cursor: pointer;
}

.card.clickable:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card.clickable:hover::before {
  opacity: 1;
}

.card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 12px;
}

.name {
  font-size: 18px;
  font-weight: 700;
  color: var(--dark);
  line-height: 1.3;
  margin-right: 10px;
  flex: 1;
}

.badge {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  white-space: nowrap;
}

/* 状态色 */
.badge.s-approved {
  background: #e8f6ec;
  color: #0a7a2e;
}

.badge.s-reviewing {
  background: #fff7e6;
  color: #a15f00;
}

.badge.s-notApproved {
  background: #fdecee;
  color: #a80618;
}

.meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: var(--text-light);
  font-size: 14px;
  margin-bottom: 8px;
}

.meta span {
  display: flex;
  align-items: center;
  gap: 6px;
}

.meta-icon {
  font-size: 14px;
}

.open {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
}

.status-dot.on {
  background: #0a7a2e;
}

.open.on {
  color: #0a7a2e;
  font-weight: 600;
}

.tip {
  margin-top: 12px;
  color: var(--text-light);
  font-size: 13px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid var(--warning);
}

/* 加载状态 */
.state {
  text-align: center;
  color: var(--text-light);
  padding: 60px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(67, 97, 238, 0.2);
  border-left: 4px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.7;
}

.state p {
  margin: 4px 0;
}

.state.empty i {
  font-style: normal;
  color: var(--primary);
  font-weight: 600;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .topbar-content {
    padding: 0 16px;
    height: 60px;
  }

  .title {
    font-size: 18px;
  }

  .topbar-actions {
    gap: 8px;
  }

  .add,
  .logout-btn {
    height: 36px;
    padding: 0 12px;
    font-size: 13px;
  }

  .container {
    padding: 16px;
    padding-bottom: calc(14vw + 16px);
  }

  .tabs {
    margin-bottom: 20px;
  }

  .tab {
    padding: 6px 12px;
    font-size: 14px;
  }

  .card {
    padding: 16px;
  }

  .action-bar {
    gap: 8px;
    margin-bottom: 20px;
  }
  
  .wallet-btn, .add {
    height: 40px;
    padding: 0 16px;
    font-size: 14px;
  }
  
  .wallet-icon, .add-icon {
    font-size: 16px;
  }
}
</style>